<template>
  <div class="form-page">
    <Form ref="formModel" :rules="ruleValidate" :model="bloc.form" :label-width="100" label-position="right">
      <FormItem label="角色名称:" prop="name" required>
        <Input type="text" placeholder="请填写角色名称" v-model="bloc.form.name"/>
      </FormItem>
      <FormItem label="角色描述:" prop="description" required>
        <Input type="textarea" :rows="4" v-model="bloc.form.description" placeholder="请填写角色描述"/>
      </FormItem>
    </Form>
    <div class="footer">
      <Button @click="handleCancel">取消</Button>
      <Button ref="handleOk" type="primary"
              @click="handleOk">确定
      </Button>
    </div>
  </div>
</template>

<script lang="ts">
  import {Component, Prop, Vue} from 'vue-property-decorator';
  import {FormRoleBloc} from '@/view/role/bloc/FormRoleBloc';
  import {Button} from 'view-design';

  @Component
  export default class FormRoleModal extends Vue {
    @Prop({type: Boolean})
    readonly showRoleModal!: boolean;
    @Prop({type: Number})
    readonly idx!: number;

    bloc: FormRoleBloc = new FormRoleBloc();
    ruleValidate = {
      name: [
        {required: true, message: '角色名称不能为空', trigger: 'blur'}
      ],
      description: [
        {required: true, message: '角色描述不能为空', trigger: 'blur'}
      ]
    };

    $refs!: {
      handleOk: Button
    };

    handleOk() {
      const formRef: any = this.$refs['formModel'];
      formRef.validate((valid) => {
        if (valid) {
          this.$refs.handleOk.loading = true;
          this.bloc.save().then(res => {
            this.$Message.success('保存成功');
            this.$emit('on-ok', res.data);
          }).catch(err => {
            console.log('save failed.', err);
            this.$Message.error(err.message || '保存失败');
          }).finally(() => {
            this.$refs.handleOk.loading = false;
          });
        }
      });
    }

    handleCancel() {
      const formRef: any = this.$refs['formModel'];
      formRef.resetFields();
      this.$emit('on-cancel');
    }
  }
</script>

<style lang="less" scoped>
</style>
